package com.lk.template.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.lk.template.exception.CommonException;
import com.lk.template.exception.R;
import com.lk.template.service.OssFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;


/**
 * @author lk
 * @date 2024/2/22 17:42
 */
@Service
public class OssFileServiceImpl implements OssFileService {

  @Value("${spring.cloud.alicloud.access-key}")
  private String accessKeyId;
  @Value("${spring.cloud.alicloud.secret-key}")
  private String accessKeySecret;
  @Value("${spring.cloud.alicloud.oss.endpoint}")
  private String endpoint;
  @Value("${spring.cloud.alicloud.oss.bucket}")
  private String bucket;
  @Value("${spring.cloud.alicloud.oss.host}")
  private String host;

  /**
   * 阿里云OSS的上传凭证
   *
   * @return
   */
  @Override
  public R getOssFileToken() {
    //目录
    String dir = DateUtil.today();
    //ossClient实例
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    try {
      //过期时间
      long expireTime = 3000;
      long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
      Date expiration = new Date(expireEndTime);
      PolicyConditions policyConditions = new PolicyConditions();
      policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
      policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
      //策略和签名
      String postPolicy = ossClient.generatePostPolicy(expiration, policyConditions);
      byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
      String encodedPolicy = BinaryUtil.toBase64String(binaryData);
      String postSignature = ossClient.calculatePostSignature(postPolicy);

      Map<String, String> respMap = new LinkedHashMap<String, String>();
      respMap.put("accessId", accessKeyId);
      respMap.put("policy", encodedPolicy);
      respMap.put("signature", postSignature);
      respMap.put("dir", dir);
      respMap.put("host", host);
      respMap.put("expire", String.valueOf(expireEndTime / 1000));
      return R.ok(respMap);
    } catch (Exception e) {
      throw new CommonException("获取上传令牌失败");
    }
  }

  /**
   * 上传文件
   */
  @Override
  public String ossUploadFile(MultipartFile file) {
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    final String filename = file.getOriginalFilename();
    Snowflake snowflake = IdUtil.getSnowflake(1, 1);
    String dir = "";
    if(!ObjectUtils.isEmpty(filename)){
      dir = DateUtil.today() + "/" + snowflake.nextIdStr() + filename.substring(filename.lastIndexOf("."));
    }
    try {
      PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, dir, file.getInputStream());
      ossClient.putObject(putObjectRequest);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (ossClient != null) {
        ossClient.shutdown();
      }
    }
    return dir;
  }

//  /**
//   * 并发上传文件
//   */
//  public String ossUploadFile(MultipartFile file) {
//    OSS ossClient = null;
//    final String filename = file.getOriginalFilename();
//    Snowflake snowflake = IdUtil.getSnowflake(1, 1);
//    String dir = "";
//    if(!ObjectUtils.isEmpty(filename)){
//      dir = DateUtil.today() + "/" + snowflake.nextIdStr() + filename.substring(filename.lastIndexOf("."));
//    }
//    try {
//      // 连接池
//      ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
//      conf.setIdleConnectionTime(1000L);
//      GenericObjectPoolConfig<HttpClient> poolConfig = new GenericObjectPoolConfig<>();
//      poolConfig.setMaxTotal(100);
//      poolConfig.setMaxIdle(50);
//      poolConfig.setMinIdle(10);
//      poolConfig.setTestOnCreate(true);
//      poolConfig.setTestOnBorrow(true);
//      poolConfig.setTestOnReturn(true);
//      poolConfig.setTestWhileIdle(true);
//      poolConfig.setTimeBetweenEvictionRunsMillis(5000);
//
//      ossClient = new OSSClientBuilder()
//        .setEndpoint(endpoint)
//        .setCredentialsProvider(new DefaultCredentialProvider(accessKeyId, accessKeySecret))
//        .setConf(conf)
//        .setConnectionPoolConfig(poolConfig)
//        .build();
//
//      PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, dir, file.getInputStream());
//      ossClient.putObject(putObjectRequest);
//    } catch (Exception e) {
//      // 异常处理
//      throw new RuntimeException("Failed to upload file: " + e.getMessage(), e);
//    } finally {
//      if (ossClient != null) {
//        ossClient.shutdown();
//      }
//    }
//    return dir;
//  }

  /**
   * 批量上传
   */
  @Override
  public List<String> ossUploadFileList(MultipartFile[] file) {
    final ArrayList<String> list = new ArrayList<>();
    for (MultipartFile multipartFile : file) {
      list.add(ossUploadFile(multipartFile));
    }
    return list;
  }

}
